package com.ruoyi.system.controller;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.apache.commons.compress.utils.Lists;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.system.domain.TotalSite;
import com.ruoyi.system.entity.ExitNums;
import com.ruoyi.system.service.IExitService;
import com.ruoyi.system.service.IStopService;
import com.ruoyi.system.service.ITotalSiteService;
import com.ruoyi.system.vo.ExitNumResult;
import com.ruoyi.system.vo.Geojson;
import com.ruoyi.system.vo.Geometry;
import com.ruoyi.system.vo.Properties;

import cn.hutool.core.bean.BeanUtil;

/**
 * 全部总数据Controller
 * 
 * @author zhangkai
 * @date 2021-11-22
 */
@RestController
@RequestMapping("/tietasystem/index")
public class IndexChartController extends BaseController {
	@Autowired
	private ITotalSiteService totalSiteService;

	@Autowired
	private IExitService exitService;
	
	@Autowired
    private IStopService stopService;

	/**
     * 首页-获取退服数量
     */
	@GetMapping(value = "/chartExitNums")
	public AjaxResult chartExitNums() {
		String[] areaNames = { "沈阳", "大连", "鞍山", "抚顺", "本溪", "丹东", "锦州", "营口", "阜新", "辽阳", "盘锦", "铁岭", "朝阳", "葫芦岛" };
		Integer[] exitCommonNums = new Integer[14];
		Integer[] exitImportantNums = new Integer[14];

		// 退服普通数量
		Map<String, Integer> commonMap = new HashMap<>();
		// 退服重点数量
		Map<String, Integer> importantMap = new HashMap<>();
		
		String version = exitService.maxVersion();
		
		exitService.getNums(version).forEach(f -> {
			if("important".equals(f.getFlag()))
				importantMap.put(f.getAlarmCity(), f.getNum());
			if("common".equals(f.getFlag()))
				commonMap.put(f.getAlarmCity(), f.getNum());
		});

		for (int i = 0; i < areaNames.length; i++) {

			if (commonMap.get(areaNames[i]) != null) {
				exitCommonNums[i] = commonMap.get(areaNames[i]);
			} else {
				exitCommonNums[i] = 0;
			}
			if (importantMap.get(areaNames[i]) != null) {
				exitImportantNums[i] = importantMap.get(areaNames[i]);
			} else {
				exitImportantNums[i] = 0;
			}
		}

		ExitNumResult nums = new ExitNumResult();
		nums.setAreaNames(areaNames);
		nums.setExitCommonNums(exitCommonNums);
		nums.setExitImportantNums(exitImportantNums);

		return AjaxResult.success(version, nums);
	}
	
	/**
     * 首页-获取地图数据
     */
	@GetMapping(value = "/chartStatistics")
    public AjaxResult chartStatistics(String datatype){
		
		if(StringUtils.isEmpty(datatype)) return AjaxResult.error("datatype value is not null !!!");
		
		List<Geojson> allList = Lists.newArrayList();
		if("exit".equals(datatype.toLowerCase())){
			String version = exitService.maxVersion();
			String beginTime =  version.substring(0,8) + "00";
			String endTime =  version.substring(0,8) + "99";
			allList = totalSiteService.indexStatisticsExit(beginTime, endTime).stream().map(m -> {
				Geojson json = new Geojson();
				json.setType(m.getFlag());
				
				Geometry geometry = new Geometry();
				geometry.setCoordinates(new String[]{m.getLongitude() ,m.getLatitude()});
				json.setGeometry(geometry);
				
				Properties properties = new Properties();
				properties.putAll(BeanUtil.beanToMap(m));
				json.setProperties(properties);
				return json;
			}).collect(Collectors.toList());
			
			
		} else if("stop".equals(datatype.toLowerCase())){
			String version = stopService.maxVersion();
			String beginTime =  version.substring(0,8) + "00";
			String endTime =  version.substring(0,8) + "99";
			allList = totalSiteService.indexStatisticsStop(beginTime, endTime).stream().map(m -> {
				Geojson json = new Geojson();
				json.setType(m.getFlag());
				
				Geometry geometry = new Geometry();
				geometry.setCoordinates(new String[]{m.getLongitude() ,m.getLatitude()});
				json.setGeometry(geometry);
				
				Properties properties = new Properties();
				properties.putAll(BeanUtil.beanToMap(m));
				json.setProperties(properties);
				return json;
			}).collect(Collectors.toList());
			
		} else {
			return AjaxResult.error("datatype param is error, please check it !!!");
			/*//获取当日时间
			String beginTime = new SimpleDateFormat("yyyyMMdd00").format(Calendar.getInstance().getTime());
			String endTime = new SimpleDateFormat("yyyyMMdd99").format(Calendar.getInstance().getTime());
			allList = totalSiteService.indexStatisticsTotal(beginTime, endTime).stream().map(m -> {
				Geojson json = new Geojson();
				json.setType(m.getFlag());
				
				Geometry geometry = new Geometry();
				geometry.setCoordinates(new String[]{m.getLongitude() ,m.getLatitude()});
				json.setGeometry(geometry);
				
				Properties properties = new Properties();
				properties.putAll(BeanUtil.beanToMap(m));
				json.setProperties(properties);
				return json;
			}).collect(Collectors.toList());*/
		}
		
		//返回结果
		List<Map<String, List<Geojson>>> resultList = Lists.newArrayList();
		Map<String, List<Geojson>> mapHour = new HashMap<>();
		String tmpStr = "";
		List<Geojson> tmpList = Lists.newArrayList();
		int count = 0;
		for(Geojson bean : allList){
			if("".equals(tmpStr)){
				tmpList.add(bean);
			} else {
				if(tmpStr.equals(bean.getProperties().get("version").toString())){
					tmpList.add(bean);
				} else {
					mapHour.put(tmpStr, tmpList);
					resultList.add(mapHour);
					mapHour = new HashMap<>();
					tmpList = Lists.newArrayList();
					tmpList.add(bean);
				}
			}
			tmpStr = bean.getProperties().get("version").toString();
			count++;
			if(count == allList.size()) {
				mapHour.put(tmpStr, tmpList);
				resultList.add(mapHour);
			}
		}
		
		return AjaxResult.success(resultList);
	}
	
	/**
     * 首页-获取地图数据
     */
	@GetMapping(value = "/searchStatistics")
    public AjaxResult searchStatistics(String datatype, String begintime, String endtime){
		
		if(StringUtils.isEmpty(datatype)) return AjaxResult.error("datatype value is not null !!!");
		
		List<Geojson> allList = Lists.newArrayList();
		if("exit".equals(datatype.toLowerCase())){
			String beginTime = StringUtils.isEmpty(begintime)?"0000000000":begintime;
			String endTime =  StringUtils.isEmpty(endtime)?"9999999999":endtime;
			allList = totalSiteService.indexStatisticsExit(beginTime, endTime).stream().map(m -> {
				Geojson json = new Geojson();
				json.setType(m.getFlag());
				
				Geometry geometry = new Geometry();
				geometry.setCoordinates(new String[]{m.getLongitude() ,m.getLatitude()});
				json.setGeometry(geometry);
				
				Properties properties = new Properties();
				properties.putAll(BeanUtil.beanToMap(m));
				json.setProperties(properties);
				return json;
			}).collect(Collectors.toList());
			
			
		} else if("stop".equals(datatype.toLowerCase())){
			String beginTime = StringUtils.isEmpty(begintime)?"0000000000":begintime;
			String endTime =  StringUtils.isEmpty(endtime)?"9999999999":endtime;
			allList = totalSiteService.indexStatisticsStop(beginTime, endTime).stream().map(m -> {
				Geojson json = new Geojson();
				json.setType(m.getFlag());
				
				Geometry geometry = new Geometry();
				geometry.setCoordinates(new String[]{m.getLongitude() ,m.getLatitude()});
				json.setGeometry(geometry);
				
				Properties properties = new Properties();
				properties.putAll(BeanUtil.beanToMap(m));
				json.setProperties(properties);
				return json;
			}).collect(Collectors.toList());
			
		} else {
			return AjaxResult.error("datatype param is error, please check it !!!");
		}
		
		//返回结果
		List<Map<String, List<Geojson>>> resultList = Lists.newArrayList();
		Map<String, List<Geojson>> mapHour = new HashMap<>();
		String tmpStr = "";
		List<Geojson> tmpList = Lists.newArrayList();
		int count = 0;
		for(Geojson bean : allList){
			if("".equals(tmpStr)){
				tmpList.add(bean);
			} else {
				if(tmpStr.equals(bean.getProperties().get("version").toString())){
					tmpList.add(bean);
				} else {
					mapHour.put(tmpStr, tmpList);
					resultList.add(mapHour);
					mapHour = new HashMap<>();
					tmpList = Lists.newArrayList();
					tmpList.add(bean);
				}
			}
			tmpStr = bean.getProperties().get("version").toString();
			count++;
			if(count == allList.size()) {
				mapHour.put(tmpStr, tmpList);
				resultList.add(mapHour);
			}
		}
		
		return AjaxResult.success(resultList);
	}
	
	/**
     * 清空缓存
     */
	@GetMapping(value = "/cache/refresh")
    public AjaxResult cacheClean(){
		totalSiteService.cacheClean();
		exitService.cacheClean();
		stopService.cacheClean();
		return AjaxResult.success("cache data is clean!!!");
	}

}
